package com.gemom.util;

import java.util.*;
import java.text.NumberFormat;

import patch.apache.commons.math.stat.correlation.Covariance;
import patch.apache.commons.math.linear.RealMatrix;

import org.jfree.data.statistics.*; 

/**
 *
 * @author Yair Diaz
 */
public class CovMatrixData {

    private double[][]covMatrix;//this is the covariance matrix
    private RealMatrix rMatrix;
    double[][]meanAndStdDev;
    double [][]seriesData;
    
    public CovMatrixData(double [][]seriesData){
        
        this.seriesData = seriesData;
        
        Covariance cov = new Covariance(seriesData);
        rMatrix = cov.getCovarianceMatrix();
        covMatrix = rMatrix.getData();
    }
    
    public void printCovMatrix(){
        
         NumberFormat nf = NumberFormat.getInstance();
         nf.setMaximumFractionDigits(2);
         
         for(int i=0;i<covMatrix.length;i++)
         {for(int k=0;k<covMatrix.length;k++)
                 System.out.print(nf.format(covMatrix[i][k])+"  ");
         System.out.println();
         }
        
    }
    
    public double calculateVarsetItems(int... itemV){
        
        int[]items=itemV;
        Arrays.sort(items);
        double var=0;
        
        // var(x)+var(y)+var(z)+...
        for(int i=0;i<items.length;i++)
            var+=covMatrix[items[i]][items[i]];
        
        //2Cov(x,y) + 2Cov(x,z) +....
        for(int i=0;i<items.length;i++)
         {for(int k=i+1;k<items.length;k++)
            {var+= 2*covMatrix[items[i]][items[k]];}}
        //System.out.println(var);
        return var;
    }

   public void calculateMeanAndStdDev(){
    
        Number[][] seriesNumber = new Number[seriesData[0].length][seriesData.length];
         meanAndStdDev = new double[2][seriesData[0].length];
         
        for(int i=0;i<seriesData[0].length;i++)
            {for(int j=0;j<seriesData.length;j++)
                { seriesNumber[i][j]=seriesData[j][i];}
             meanAndStdDev[0][i]=Statistics.calculateMean(seriesNumber[i]);
             meanAndStdDev[1][i]=Statistics.getStdDev(seriesNumber[i]);
            }
     }
    
   public double[][] getMeanAndStdDev(){ return meanAndStdDev; } 
    
    public double[][] getCovMatrix(){return covMatrix;}
    
}
